<template>
  <view class="register-container">
    <!-- 顶部医生信息 -->
    <view class="doctor-info-card">
      <image class="doctor-avatar" :src="config.staticUrl + (doctor.imgUrl || '/static/images/default-avatar.png')"></image>
      <view class="doctor-info">
        <text class="doctor-name">{{ doctor.name }}</text>
        <text class="doctor-title">{{ doctor.jobTitle }}</text>
        <text class="doctor-dept">{{ doctor.departmentName }}</text>
      </view>
    </view>

    <!-- 挂号步骤 -->
    <view class="steps-indicator">
      <view :class="['step-item', { 'active': currentStep === 1 }]">
        <text class="step-number">1</text>
        <text class="step-text">选择时间</text>
      </view>
      <view class="step-separator"></view>
      <view :class="['step-item', { 'active': currentStep === 2 }]">
        <text class="step-number">2</text>
        <text class="step-text">确认信息</text>
      </view>
    </view>

    <!-- 主内容区域 -->
    <scroll-view scroll-y class="main-content-scroll">
      <!-- 步骤1: 选择时间 -->
      <view v-if="currentStep === 1" class="step-section">
        <view class="section-title">选择就诊时间</view>
        
        <!-- 日历视图 -->
        <view class="calendar-view">
          <view class="calendar-header">
            <button class="icon-arrow" @tap="changeMonth(-1)">&#8592;</button>
            <text class="current-month">{{ displayYear }}年{{ displayMonth.toString().padStart(2, '0') }}月</text>
            <button class="icon-arrow" @tap="changeMonth(1)">&#8594;</button>
          </view>
          <view class="weekdays">
            <text>日</text>
            <text>一</text>
            <text>二</text>
            <text>三</text>
            <text>四</text>
            <text>五</text>
            <text>六</text>
          </view>
          <view class="dates-grid">
            <text v-for="(dateItem, index) in calendarDates" :key="index"
                  :class="['date-item', { 
                    'today': dateItem.isToday, 
                    'selected': selectedDate === dateItem.date, 
                    'isPlaceholder': dateItem.isPlaceholder 
                  }]"
                  @tap="selectDate(dateItem.date)">
              {{ dateItem.isPlaceholder ? '' : new Date(dateItem.date).getDate() }}
            </text>
          </view>
        </view>
        
        <!-- 时间段选择 -->
        <view class="time-slot-selection">
          <view v-if="availableSlots.length === 0 && selectedDate" class="no-slots-message">
            <text>当前日期暂无可用号源，请选择其他日期。</text>
          </view>
          <view v-if="!selectedDate" class="no-slots-message">
            <text>请先选择日期以查看可用时间段。</text>
          </view>
          
          <view :class="['time-slot-item', { 
                  'selected': selectedSlotId === slot.slotId, 
                  'disabled': Number(slot.bookedCount) >= Number(slot.totalCapacity) 
                }]"
                v-for="(slot, index) in availableSlots" :key="slot.slotId" 
                @tap="selectTimeSlot(slot)">
            <text>{{ slot.time_slot }}</text>
            <text>{{ slot.bookedCount < slot.totalCapacity ? `(余${slot.totalCapacity - slot.bookedCount})` : '(已满)' }}</text>
          </view>
        </view>
        
        <button class="next-step-btn" @tap="nextStep" :disabled="!selectedDate || !selectedSlotId">下一步</button>
      </view>

      <!-- 步骤2: 确认信息 -->
      <view v-if="currentStep === 2" class="step-section">
        <view class="section-title">确认挂号信息</view>
        
        <view class="confirmation-details">
          <view class="detail-item">
            <text class="label">医生:</text>
            <text class="value">{{ doctor.name }}</text>
          </view>
          <view class="detail-item">
            <text class="label">科室:</text>
            <text class="value">{{ doctor.departmentName }}</text>
          </view>
          <view class="detail-item">
            <text class="label">医院:</text>
            <text class="value">{{ doctor.hospitalName }}</text>
          </view>
          <view class="detail-item">
            <text class="label">日期:</text>
            <text class="value">{{ selectedDate }}</text>
          </view>
          <view class="detail-item">
            <text class="label">时间段:</text>
            <text class="value">{{ selectedTimeSlot }}</text>
          </view>
          
          <!-- 就诊原因 -->
          <view class="form-item">
            <input v-model="reasonForVisit" placeholder="请输入就诊原因 (可选)" type="text" />
          </view>
        </view>
        
        <button class="confirm-btn" @tap="confirmRegistration">确认挂号</button>
        <button class="prev-step-btn" @tap="prevStep">上一步</button>
      </view>
    </scroll-view>

    <!-- 底部信息汇总 -->
    <view class="bottom-summary" v-if="currentStep === 1">
      <view class="summary-item">
        <text class="summary-label">医生:</text>
        <text class="summary-value">{{ doctor.name }}</text>
      </view>
      <view class="summary-item">
        <text class="summary-label">时间:</text>
        <text class="summary-value">{{ selectedDate ? selectedDate + ' ' + selectedTimeSlot : '待选' }}</text>
      </view>
    </view>
    
    <!-- 挂号成功弹窗 -->
    <uni-popup ref="successPopup" type="center">
      <view class="success-popup">
        <text class="iconfont icon-success success-icon"></text>
        <text class="success-title">挂号成功</text>
        <text class="success-text">您的挂号信息已提交，请按时就诊</text>
        <button class="confirm-btn" @tap="closePopup">确定</button>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { listSlot } from '@/api/slot.js';
import { addAppointment } from '@/api/appointment.js';
import { getInfoDoctor } from '@/api/doctor.js';
import config from '@/config.js';

export default {
  data() {
    const today = new Date();
    return {
      currentStep: 1,
      doctor: {
        id: '',
        name: '',
        jobTitle: '',
        departmentName: '',
        departmentId: '',
        hospitalId: '',
        hospitalName: '',
        imgUrl: ''
      },
      availableSlots: [],
      selectedDate: '',
      selectedTimeSlot: '',
      selectedSlotId: null,
      displayYear: today.getFullYear(),
      displayMonth: today.getMonth() + 1,
      reasonForVisit: '',
      config: config,
      loading: true
    };
  },
  computed: {
    calendarDates() {
      const year = this.displayYear;
      const month = this.displayMonth;
      const today = new Date();
      const currentFullDate = `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`;

      const firstDayOfMonth = new Date(year, month - 1, 1);
      const lastDayOfMonth = new Date(year, month, 0);
      const daysInMonth = lastDayOfMonth.getDate();

      const dates = [];
      // 填充上个月的空白
      const firstDayOfWeek = firstDayOfMonth.getDay();
      for (let i = 0; i < firstDayOfWeek; i++) {
        dates.push({ date: '', isPlaceholder: true });
      }

      for (let i = 1; i <= daysInMonth; i++) {
        const dateStr = `${year}-${month.toString().padStart(2, '0')}-${i.toString().padStart(2, '0')}`;
        dates.push({
          date: dateStr,
          isToday: dateStr === currentFullDate,
          isPlaceholder: false
        });
      }
      return dates;
    }
  },
  onLoad(options) {
    this.doctor.id = options.doctorId || '';
    this.doctor.name = options.doctorName || '';
    this.doctor.departmentId = options.departmentId || '';
    this.doctor.hospitalId = options.hospitalId || '';
    
    // 获取医生详细信息
    this.getDoctorDetail();
  },
  methods: {
    async getDoctorDetail() {
      if (!this.doctor.id) return;
      
      try {
        const res = await getInfoDoctor(this.doctor.id);
        if (res.code === 200 && res.data) {
          this.doctor = {
            ...this.doctor,
            ...res.data
          };
          this.loading = false;
        } else {
          uni.showToast({
            title: res.msg || '获取医生详情失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取医生详情失败:', error);
        uni.showToast({
          title: '获取医生详情失败',
          icon: 'none'
        });
      }
    },
    
    selectDate(date) {
      if (!date) return;
      this.selectedDate = date;
      this.selectedTimeSlot = '';
      this.selectedSlotId = null;
      this.fetchAvailableSlots();
    },
    
    async fetchAvailableSlots() {
      if (!this.doctor.id || !this.selectedDate) return;
      
      try {
        const res = await listSlot({
          doctorId: this.doctor.id,
          scheduleDate: this.selectedDate
        });
        
        if (res.code === 200 && res.rows) {
          this.availableSlots = res.rows.map(slot => ({
            ...slot,
            bookedCount: Number(slot.bookedCount),
            totalCapacity: Number(slot.totalCapacity)
          }));
        } else {
          this.availableSlots = [];
          uni.showToast({ title: res.msg || '暂无可用号源', icon: 'none' });
        }
      } catch (error) {
        console.error('获取号源失败:', error);
        this.availableSlots = [];
        uni.showToast({ title: '获取号源失败', icon: 'none' });
      }
    },
    
    selectTimeSlot(slot) {
      if (slot.bookedCount < slot.totalCapacity) {
        this.selectedTimeSlot = slot.time_slot;
        this.selectedSlotId = slot.slotId;
      } else {
        uni.showToast({ title: '该时间段已满', icon: 'none' });
      }
    },
    
    changeMonth(offset) {
      let newMonth = this.displayMonth + offset;
      let newYear = this.displayYear;

      if (newMonth > 12) {
        newMonth = 1;
        newYear++;
      } else if (newMonth < 1) {
        newMonth = 12;
        newYear--;
      }
      
      this.displayMonth = newMonth;
      this.displayYear = newYear;
      this.selectedDate = '';
      this.selectedTimeSlot = '';
      this.selectedSlotId = null;
      this.availableSlots = [];
    },
    
    nextStep() {
      if (this.currentStep === 1 && this.selectedDate && this.selectedSlotId) {
        this.currentStep = 2;
      }
    },
    
    prevStep() {
      if (this.currentStep > 1) {
        this.currentStep--;
      }
    },
    
    async confirmRegistration() {
      if (!this.selectedSlotId) {
        uni.showToast({ title: '请完善挂号信息', icon: 'none' });
        return;
      }
      
      const registrationData = {
        slotId: this.selectedSlotId,
        doctorId: this.doctor.id,
        departmentId: this.doctor.departmentId,
        hospitalId: this.doctor.hospitalId,
        appointmentDate: this.selectedDate,
        appointmentTimeSlot: this.selectedTimeSlot,
        reasonForVisit: this.reasonForVisit,
        status: '待确认'
      };
      
      try {
        const res = await addAppointment(registrationData);
        if (res.code === 200) {
          this.$refs.successPopup.open();
        } else {
          uni.showToast({ title: res.msg || '挂号失败', icon: 'none' });
        }
      } catch (error) {
        console.error('挂号失败:', error);
        uni.showToast({ title: '挂号请求失败', icon: 'none' });
      }
    },
    
    closePopup() {
      this.$refs.successPopup.close();
      uni.navigateBack();
    }
  }
};
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

/* 医生信息卡片 */
.doctor-info-card {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.doctor-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  margin-right: 30rpx;
  object-fit: cover;
}

.doctor-info {
  flex: 1;
}

.doctor-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.doctor-title {
  font-size: 28rpx;
  color: #666;
  margin-right: 20rpx;
}

.doctor-dept {
  font-size: 28rpx;
  color: #666;
}

/* 步骤指示器 */
.steps-indicator {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 40rpx;
  background-color: #fff;
  color: #333;
  font-size: 28rpx;
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
}

.step-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  text-align: center;
  opacity: 0.6;
}

.step-item.active {
  opacity: 1;
  font-weight: bold;
}

.step-number {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background-color: #eee;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 8rpx;
  font-size: 24rpx;
}

.step-item.active .step-number {
  background-color: #4B7BFF;
  color: #fff;
}

.step-separator {
  width: 80rpx;
  height: 2rpx;
  background-color: #eee;
  margin: 0 10rpx;
  margin-bottom: 20rpx;
}

/* 主内容区域 */
.main-content-scroll {
  flex: 1;
  padding: 20rpx 30rpx;
  box-sizing: border-box;
}

.step-section {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

/* 日历和时间段选择样式 */
.calendar-view {
  background-color: #f0f8ff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  text-align: center;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 10rpx;
  margin-bottom: 15rpx;
  font-size: 26rpx;
  color: #999;
}

.dates-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 10rpx;
}

.date-item {
  width: 70rpx;
  height: 70rpx;
  line-height: 70rpx;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28rpx;
  color: #333;
  background-color: #fff;
}

.date-item.today {
  border: 2rpx solid #4B7BFF;
  color: #4B7BFF;
  font-weight: bold;
}

.date-item.selected {
  background-color: #4B7BFF;
  color: #fff;
}

.date-item.isPlaceholder {
  background-color: transparent;
  color: #ccc;
  pointer-events: none;
}

.time-slot-selection {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.time-slot-item {
  background-color: #f9f9f9;
  border: 2rpx solid #eee;
  border-radius: 16rpx;
  padding: 20rpx;
  text-align: center;
  font-size: 28rpx;
  color: #333;
}

.time-slot-item.selected {
  border-color: #4B7BFF;
  box-shadow: 0 0 15rpx rgba(75, 123, 255, 0.3);
  background-color: #e6f0ff;
}

.time-slot-item.disabled {
  background-color: #e9ecef;
  color: #999;
  border-color: #dee2e6;
  opacity: 0.7;
}

.no-slots-message {
  text-align: center;
  color: #999;
  font-size: 28rpx;
  padding: 30rpx;
  grid-column: 1 / -1;
}

/* 确认信息区域 */
.confirmation-details {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.detail-item {
  display: flex;
  align-items: center;
  font-size: 28rpx;
}

.detail-item .label {
  font-weight: bold;
  color: #666;
  width: 120rpx;
  flex-shrink: 0;
}

.detail-item .value {
  color: #333;
  flex: 1;
}

.form-item {
  margin-top: 20rpx;
  border: 1rpx solid #eee;
  border-radius: 12rpx;
  padding: 20rpx;
}

.form-item input {
  width: 100%;
  font-size: 28rpx;
  color: #333;
}

/* 按钮样式 */
.next-step-btn, .confirm-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 45rpx;
  background-color: #4B7BFF;
  color: #fff;
  font-size: 32rpx;
  margin-top: 30rpx;
  text-align: center;
}

.next-step-btn[disabled] {
  background-color: #a7c4ff;
  cursor: not-allowed;
}

.prev-step-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 45rpx;
  background-color: #f0f0f0;
  color: #666;
  font-size: 32rpx;
  margin-top: 20rpx;
}

/* 底部信息汇总 */
.bottom-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
  box-shadow: 0 -4rpx 10rpx rgba(0, 0, 0, 0.05);
}

.summary-item {
  display: flex;
  flex-direction: column;
  font-size: 24rpx;
  flex: 1;
  text-align: center;
}

.summary-label {
  color: #999;
  margin-bottom: 5rpx;
}

.summary-value {
  color: #333;
  font-weight: bold;
}

/* 成功弹窗 */
.success-popup {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  width: 600rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.success-icon {
  font-size: 100rpx;
  color: #4BB543;
  margin-bottom: 30rpx;
}

.success-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.success-text {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 30rpx;
  text-align: center;
}

.confirm-btn {
  width: 100%;
  margin-top: 0;
}
</style>